﻿using System;
using System.Diagnostics;

namespace zijian666.Core
{
    /// <summary>
    /// 异常信息
    /// </summary>
    [DebuggerDisplay("{" + nameof(GetDebuggerDisplay) + "(),nq}")]
    public readonly struct ErrorInfo
    {
        /// <summary>
        /// 异常对象
        /// </summary>
        public readonly Exception Exception;
        /// <summary>
        /// 异常产生类
        /// </summary>
        public readonly Type Owner;
        /// <summary>
        /// 上下文参数
        /// </summary>
        public readonly object Context;
        /// <summary>
        /// 异常类成员
        /// </summary>
        public readonly string MemberName;
        /// <summary>
        /// 异常源码文件名
        /// </summary>
        public readonly string FilePath;
        /// <summary>
        /// 异常类源码文件行号
        /// </summary>
        public readonly int LineNumber;
        /// <summary>
        /// 构造函数
        /// </summary>
        public ErrorInfo(Exception exception, Type owner, object context, string memberName, string filePath, int lineNumber)
        {
            Exception = exception ?? throw new ArgumentNullException(nameof(exception));
            Owner = owner ?? Exception.TargetSite?.ReflectedType;
            Context = context;
            FilePath = filePath ?? Exception.TargetSite?.ReflectedType?.AssemblyQualifiedName;
            MemberName = memberName ?? Exception.TargetSite?.Name;
            LineNumber = lineNumber;
        }

        public override string ToString() =>
$@"{FilePath}.{MemberName} : {LineNumber}
Type: {Owner?.FullName}
Context: {Context ?? "`null`"}
Exception: {Exception.Message}
StackTrace: {Exception.StackTrace}";

        private string GetDebuggerDisplay() => ToString();
    }
}
